<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>

          <a-col :span="24">
            <a-form-model-item label="联系人姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入联系人姓名"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="telephones">
              <a-button class="editable-add-btn" @click="telAdd">
                新增
              </a-button>
              <a-table
                bordered
                :dataSource="dataSource"
                :columns="columns"
                :pagination="false"
                rowKey="id"
              >
                <template slot="phone" slot-scope="text, record">
                  <editable-cell
                    :ref="`tel_${record.key}`"
                    decoratorType="integer"
                    formType="input"
                    :decoratorOptions="rules.phone"
                    :defaultEditable="true"
                    :required="true"
                    :value="text"
                    :text="text"
                    placeholder="请输入手机号"
                    :autoSave="true"
                    @valueChange="onInputChange(record.key, 'phone', $event)"
                  />
                </template>

                <template slot="type" slot-scope="text, record">
                  <editable-cell
                    :ref="`region_${record.key}`"
                    :decoratorOptions="rules.type"
                    :text="record.type"
                    :autoSave="true"
                    :defaultEditable="true"
                    :required="true"
                    :value="text"
                    formType="selectTag"
                    dictCode="telephone_type "
                    @selectTagChange="onCellChange(record.key, 'type',$event)"
                  />
                </template>
                <template slot="operation" slot-scope="text, record">
                  <a-popconfirm v-if="dataSource.length " title="确定要删除?" @confirm="() => batchDel(record)">
              <span>
                <a href="javascript:;">删除</a>

              </span>
                  </a-popconfirm>

                </template>
              </a-table>
            </a-form-model-item>

          </a-col>
          <a-col :span="24">
            <a-form-model-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="email">
              <a-input v-model="model.email" placeholder="请输入邮箱"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">


              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="QQ" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qq">
              <a-input v-model="model.qq" placeholder="请输入QQ"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
              <j-area-linkage type="cascader" v-model="model.address" placeholder="请选择省市区" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="地址详情" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="addressInfo">
              <a-input v-model="model.addressInfo" placeholder="请输入地址详情"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="邮编" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="postalCode">
              <a-input v-model="model.postalCode" placeholder="请输入邮编"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gender">
              <j-dict-select-tag type="list" v-model="model.gender" dictCode="Gender" placeholder="请选择性别" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="birthday">
              <!--              <a-input v-model="model.birthday" placeholder="请输入生日"></a-input>-->
              <j-date date-format="YYYY-MM-DD" v-model="model.birthday" class="jdateStyle"></j-date>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="爱好" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="hobby">
              <a-input v-model="model.hobby" placeholder="请输入爱好"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="department">
              <j-select-depart v-model="model.department" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="职务" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="post">
              <a-input v-model="model.post" placeholder="请输入职务"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
              <j-dict-select-tag type="list" v-model="model.level" dictCode="constacts_level" placeholder="请选择级别" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="重要程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="importance">
              <a-rate v-model="importance" @change="rateChange('importance',$event)" />

            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="决策关系" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relationBetween">
              <j-dict-select-tag type="list" v-model="model.relationBetween" dictCode="consacts_relation"
                                 placeholder="请选择决策关系" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="亲密度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="intimacy">
              <a-rate v-model="intimacy" @change="rateChange('intimacy',$event)" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import EditableCell from '@/components/EditableCell/cell'
import { checkOnlyUser } from '@api/api'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
import lianxiren from '@/components/jeecgbiz/lianxirenCustom'

export default {
  name: 'ContactsForm',
  components: {
    EditableCell,
    JSelectMultiUser,
    lianxiren,
    JSelectUserByDep
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  watch: {
    dataSource: {
      deep: true,
      handler(newValue, oldValue) {
        // console.log('newValue',newValue)
        this.model.telephones = newValue
      }
    },
    'model.customerId': {
      deep: true,
      handler(newValue, oldValue) {
        this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue
        if (!newValue) {
          this.model.contactsIds = ''
        }
      }
    }
  },
  data() {
    return {
      fixType: '',//修改类型 add为新增 edit为修改
      fixIndex: '',//修改类型的下标
      importance: 3,
      intimacy: 3,
      kehuurl: '/customer/customer/list?filed=2',
      // 选择用户查询条件配置
      selectUserQueryConfig: [
        { key: 'phone', label: '电话' }
      ],
      //联系人
      lianxirenUrl: '/sys/common/queryCustomerId?customerId=',
      lianxirenConfig: [
        { key: 'phone', label: '电话' }
      ],
      //电话表格使用=====开始
      dataSource: [],
      loading: false,
      count: 1,
      columns: [
        {
          title: '类型',//1.工作 2.手机 3.住址 4.主要 5.传真 6.其他
          dataIndex: 'type',
          width: '40%',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '电话',
          dataIndex: 'phone',
          width: '40%',
          scopedSlots: { customRender: 'phone' }
        },

        {
          title: '操作',
          dataIndex: 'operation',
          width: '20%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      //电话表格使用=====结束
      model: {},
      newList: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        customerId: [
          { required: true, message: '请选择客户名称!' }
        ],
        name: [
          { required: true, message: '请输入联系人!' }
        ],
        directorIds: [
          { required: true, message: '请选择负责人!' }
        ],
        telephones: [
          { required: true, message: '请输入电话!' },
          {
            validator: (rule, value, callback) => {
              /* if (value == '') {
                callback('不能为空')
              } */
              // console.log('telephones',value)
              for (let dataSourceElement of this.dataSource) {
                if (dataSourceElement.phone == '' || dataSourceElement.type == '') {
                  callback(false)
                }
              }
              callback()
            },
            message: '请填写完整',
            trigger: ['change']
          }
        ],
        email: [
          { required: false },
          { pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!' }
        ],
        qq: [
          { required: false },
          { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
        ],
        postalCode: [
          { required: false },
          { pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮政编码!' }
        ]
      },
      fields: [
        'phone',
        'type'
      ],
      rules: {
        type: {
          rules: [
            {
              required: true,
              message: '请选择类型',
              rigger: ['blur']
            }
          ]
        },
        phone: {
          rules: [
            {
              required: true,
              message: '请输入手机号'
            },
            {
              validator: (rule, value, callback) => {
                console.log('value.data.trim()', value.trim())
                if (value.trim() == '') {
                  callback(new Error('不能为空'))
                } else {
                  callback()
                }
                /* var reg=/^1[3456789]\d{9}$/
                if(!reg.test(value)){
                  callback(new Error("请输入正确手机号"))
                }else{
                  callback()

                } */
              },
              message: '不能为空',
              trigger: ['blur']
            }
          ]
        }
      },
      url: {
        add: '/contacts/contacts/add',
        edit: '/contacts/contacts/edit',
        queryById: '/contacts/contacts/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    rateChange(e, e1) {
      console.log(e)
      console.log(e1)
      if (e == 'importance') {
        this.model.importance = e1
      } else if (e == 'intimacy') {
        this.model.intimacy = e1
      } else {
        console.log('类型错误')
      }

    },
    telAdd() {
      const { count, dataSource } = this
      const newData = {
        key: count,
        phone: '',
        type: ''
      }
      this.dataSource = [...this.dataSource, newData]
      // this.dataSource.push(newData)
      this.count += 1
    },
    saveTEL() {
      // console.log(this.dataSource)
      // debugger
      const newData = [...this.dataSource]
      this.model.telephones = newData
    },
    batchDel(record) {
      // console.log('删除行',record)
      this.onDelete(record.key)
    },
    // 删除
    onDelete(key) {
      // 拷贝数组数据
      const dataSource = [...this.dataSource]
      // 过滤移除当前项目
      this.dataSource = dataSource.filter((item) => item.key !== key)
    },
    onInputChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value == '' ? undefined : value
        this.dataSource = dataSource
      }
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      // console.log(target)

      if (target && value == 0) {
        target[dataIndex] = value
        // dataSource[dataIndex].endDate = ''
        // dataSource[dataIndex].startDate = ''
        this.dataSource = dataSource.map((item) => {
          if (item.key === key) {
            return item
          } else {
            return item
          }
        })
      } else {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    // validateRow可以提取为公共函数
    validateRow(key, fields, callback) {
      // 查找验证是否通过
      const row = {}
      let err = false
      // forEach 对每一个验证，可以更改为some满足一个就提醒
      fields.forEach((filed) => {
        let refName = `${filed}_${key}`
        let result = this.$refs[refName].validate()
        row[filed] = result.value
        if (!result.success) {
          err = true
        }
      })
      callback(err, row)
    },
    add() {
      this.edit(this.modelDefault)

    },
    edit(record) {
      this.model = Object.assign({}, record)
      if (this.model.importance) {
        this.importance = Number(this.model.importance)
      } else {
        this.importance = 3
      }
      if (this.model.intimacy) {
        this.intimacy = Number(this.model.intimacy)
      } else {
        this.intimacy = 3
      }
      // this.model.importance = Number(record.importance)
      // this.model.intimacy = Number(record.intimacy)

      console.log('this.model', this.model)
      this.visible = true
      if (record.telephones) {
        this.dataSource = record.telephones
      }
      // console.log(typeof this.model.telephones)

    },
    submitForm() {
      console.log('this.model', this.model)
      this.model.fixType = this.fixType
      this.model.fixIndex = this.fixIndex
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          // that.confirmLoading = true
          console.log('this.model通过验证后提交', this.model)
          this.$emit('ok', this.model)
        }

      })
    }

  }

}
</script>
<style>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
  margin-right: 10px;
}

.jdateStyle {
  width: 100%;
}
</style>